﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;
using System.Data;
using Telerik.Web.UI;
using Workflow.Alerts.DAL;
using System.IO;
using System.Text;
using Workflow.Alerts.Utils;

namespace Workflow.Alerts.Sublayouts
{
    public partial class ListPage : BaseControl, IMainListView
    {
        #region Properties
        public string FilterPath { get; set; }
        public string RejectPath { get; set; }
        public string PartApprovePath { get; set; }
        public string DetailPath
        {
            set
            {
                DetailsPath.Value = value;
            }
        }
        #endregion

        #region IMainListView Members

        public DataRow[] Alerts
        {
            set
            {
                RadGrid1.DataSource = value;
                RadGrid1.DataBind();

                if (!value.Any())
                {
                    InvoiceButtons.Visible = false;
                }
            }
        }

        public event OnMainListViewLoad OnListLoad;

        public event OnViewChangeStatus OnChangeStatus;

        public event OnViewSaveClick OnSave;

        public event GetExcelForInvoice OnRequestExcelForInvoice;

        public event OnViewRemoveSelection OnRemoveSelection;

        public event OnSendToArchiveList SendToArchiveList;

        public string ScreenName
        {
            set { ListName.Text = value; }
        }

        #endregion

        #region Export to excel

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            GridColumn column;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colApprove");
            if (column != null) column.Visible = false;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colPartApprove");
            if (column != null) column.Visible = false;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colReject");
            if (column != null) column.Visible = false;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colAccept");
            if (column != null) column.Visible = false;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colDecline");
            if (column != null) column.Visible = false;
            column = RadGrid1.Columns.FindByUniqueNameSafe("colSend");
            if (column != null) column.Visible = false;
            RadGrid1.ExportSettings.FileName = String.Format("Workflow{0}", DateTime.Now.ToString("yyyyMMdd"));
            RadGrid1.MasterTableView.ExportToExcel();

        }
        protected void RadGrid1_ExcelExportCellFormatting(object source, ExcelExportCellFormattingEventArgs e)
        {
        }
        protected void RadGrid1_GridExporting(object source, Telerik.Web.UI.GridExportingArgs e)
        {
            foreach (string key in Translate.Words.Keys)
            {
                e.ExportOutput = e.ExportOutput.Replace(key, Translate.Words[key]);
            }
        }
        protected void CreateInvoiceReport(bool archive, List<string> ids, WorkflowEnums.Status? status)
        {
            if (OnRequestExcelForInvoice != null)
            {
                InvoiceReportCSV ir = new InvoiceReportCSV();
                ir.MunicipalityName = CurrentUser.Name;
                ir.ExportCSV(OnRequestExcelForInvoice(archive, ids, status, WorkflowEnums.InvoiceFormat.CSV));
            }
        }

        #endregion

        #region Private methods

        private void UpdateIdList()
        {
            List<int> ids = new List<int>();
            int id;
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                id = Int32.Parse(dataItem["id"].Text);
                ids.Add(id);
            }
            Session["Ids"] = ids;
        }
        private string GetSearchPath(WorkflowEnums.Status status)
        {
            var user = Session[WorkflowConstants.CurrentUser] as User;
            String page = String.Empty;
            Item detailPageItem = null;
            if (user.Type == WorkflowEnums.UserType.Municipality)
            {
                switch (status)
                {
                    case WorkflowEnums.Status.Sent:
                        page = WorkflowConstants.NewAlerts;
                        break;
                    case WorkflowEnums.Status.Approved:
                    case WorkflowEnums.Status.PartiallyApproved:
                    case WorkflowEnums.Status.Declined:
                    case WorkflowEnums.Status.Executed4Contractor:
                        page = WorkflowConstants.InProgress;
                        break;
                    case WorkflowEnums.Status.Executed4Municipality:
                        page = WorkflowConstants.Executed;
                        break;
                    case WorkflowEnums.Status.Rejected:
                    case WorkflowEnums.Status.Accepted:
                        page = WorkflowConstants.Logged;
                        break;
                }

                detailPageItem = Sitecore.Context.Item.Axes.SelectSingleItem(string.Format("/sitecore/content/workflow/{0}/Alerts/{1}/detailpage",
                                                                                           user.Name, page));
            }
            else if (user.Type == WorkflowEnums.UserType.NetworkOperator)
            {
                switch (status)
                {
                    case WorkflowEnums.Status.Created:
                        page = WorkflowConstants.Queued;
                        break;
                    case WorkflowEnums.Status.Sent:
                        page = WorkflowConstants.Sent;
                        break;
                    case WorkflowEnums.Status.PartiallyApproved:
                    case WorkflowEnums.Status.Approved:
                    case WorkflowEnums.Status.Declined:
                        page = WorkflowConstants.InProgress;
                        break;
                    case WorkflowEnums.Status.Executed4Municipality:
                    case WorkflowEnums.Status.Executed4Contractor:
                        page = WorkflowConstants.Executed;
                        break;
                    case WorkflowEnums.Status.Rejected:
                    case WorkflowEnums.Status.Accepted:
                    case WorkflowEnums.Status.Retracted:
                        page = WorkflowConstants.Logged;
                        break;
                }

                detailPageItem = Sitecore.Context.Item.Axes.SelectSingleItem(string.Format("/sitecore/content/workflow/{0}/Alerts/{1}/detailpage",
                                                                                           "NetworkOperator", page));
            }

            return Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);
        }
        private void CheckVisibilityGridColumns()
        {
            Sitecore.Data.Fields.MultilistField actionColumns = (Sitecore.Data.Fields.MultilistField)Sitecore.Context.Item.Fields["ActionColumns"];
            if (actionColumns != null)
            {
                var visibleColumns = actionColumns.GetItems();
                foreach (Item item in visibleColumns)
                {
                    var action = item.Name;
                    GridColumn column;
                    switch (action)
                    {
                        case WorkflowConstants.Status:
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colStatus");
                            if (column != null) column.Visible = true;
                            break;

                        case WorkflowConstants.ExecutedAction:
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colUnselect");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colAccept");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colDecline");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colPartAccept");
                            if (column != null) column.Visible = true;

                            break;

                        case WorkflowConstants.ReviewAction:
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colUnselect");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colApprove");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colPartApprove");
                            if (column != null) column.Visible = true;
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colReject");
                            if (column != null) column.Visible = true;

                            break;
                        case WorkflowConstants.SendAction:
                            column = RadGrid1.Columns.FindByUniqueNameSafe("colSend");
                            if (column != null)
                            {
                                column.Visible = true;
                                if (Sitecore.Context.Item.Name == WorkflowConstants.Queued)
                                    SelectionButtons.Visible = true;
                                else
                                    InvoiceButtons.Visible = true;
                            }
                            break;
                    }
                }
            }
            Sitecore.Data.Fields.MultilistField dataColumns = (Sitecore.Data.Fields.MultilistField)Sitecore.Context.Item.Fields["DataColumns"];
            if (dataColumns != null)
            {
                var visibleColumns = dataColumns.GetItems();
                foreach (Item item in visibleColumns)
                {
                    var headerName = item.Name.Replace("name", "").Trim();
                    string header = Translate.Words.ContainsKey(headerName) ? Translate.Words[headerName] : headerName;
                    string fieldName = item.Name.Replace(" ", "").ToLower();

                    GridColumn boundColumn = RadGrid1.Columns.FindByUniqueNameSafe(fieldName);
                    if (boundColumn == null)
                    {
                        boundColumn = new GridBoundColumn();
                        RadGrid1.Columns.Add(boundColumn);
                    }

                    (boundColumn as GridBoundColumn).DataFormatString = "{0:dd-MM-yyyy}";
                    boundColumn.HeaderText = header;
                    (boundColumn as GridBoundColumn).DataField = fieldName;
                    boundColumn.SortExpression = fieldName;
                    boundColumn.UniqueName = fieldName;
                    boundColumn.ShowSortIcon = false;
                }
            }

        }
        private void SetFilterButtonClass()
        {
            if (Session[WorkflowConstants.Filters] != null)
            {
                var filter = Session[WorkflowConstants.Filters] as Filter;
                if (filter.Dates != null && filter.Dates.Any() ||
                    filter.SelectedActivitiyType != null && filter.SelectedActivitiyType.Any() ||
                    filter.SelectedAlertType != null && filter.SelectedAlertType.Any() ||
                    filter.SelectedMunicipalities != null && filter.SelectedMunicipalities.Any() ||
                    filter.SelectedNetworkOperators != null && filter.SelectedNetworkOperators.Any() ||
                    filter.SelectedStatuses != null && filter.SelectedStatuses.Any())
                {
                    var style = ShowFilter.Attributes["class"];
                    style += " filterActive";
                    ShowFilter.Attributes.Add("class", style);
                }
            }
        }
        private void LoadExcelFile()
        {
            Item excelpage = Sitecore.Context.Item.Axes.SelectSingleItem("invoiceexcel");
            var url = Sitecore.Links.LinkManager.GetItemUrl(excelpage);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("var el = document.createElement(\"iframe\");");
            sb.AppendLine("el.setAttribute('id', 'ifrm');");
            sb.AppendLine("el.setAttribute('height', '0');");
            sb.AppendLine("el.setAttribute('width', '0');");
            sb.AppendLine("document.body.appendChild(el);");
            sb.AppendLine(string.Format("el.setAttribute('src', '{0}');", url));
            sb.AppendLine("</script>");
            excellabel.Text = sb.ToString();
        }
        private void UpdateAlertsStatus(string id, WorkflowEnums.Status newstatus, WorkflowEnums.Status oldstatus)
        {
            if (OnChangeStatus != null)
                OnChangeStatus(Int32.Parse(id), newstatus, oldstatus);
        }
        private void RefreshPage()
        {
            Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item));
        }
        private void SaveChanges()
        {
            if (OnSave != null)
                OnSave();
        }
        private void LoadCssClass()
        {
            if (Sitecore.Context.Item.Name == WorkflowConstants.InProgress ||
                Sitecore.Context.Item.Name == WorkflowConstants.Invoices ||
                Sitecore.Context.Item.Name == WorkflowConstants.Logged)
            {
                this.RadGrid1.MasterTableView.CssClass += " showStatus";
            }
        }

        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            PresentationManager.RegisterView(typeof(GridPresenter), this, new WebSessionProvider());
            CheckVisibilityGridColumns();

            if (OnListLoad != null)
            {
                OnListLoad();
            }

            #region Enable Map view
            Sitecore.Data.Fields.CheckboxField mapField = (Sitecore.Data.Fields.CheckboxField)Sitecore.Context.Item.Fields["Map"];
            if (mapField != null)
            {
                //check condition property on Sitecore
                if (mapField.Checked)
                {
                    Item mapPageItem = Sitecore.Context.Item.Axes.SelectSingleItem("./*[@@templatename='MapPage']");
                    MapXml.Value = Sitecore.Links.LinkManager.GetItemUrl(mapPageItem);
                }
                else
                {
                    phHideMap.Visible = true;
                }
            }
            #endregion

            #region Enable Filter
            Item filterItem = Sitecore.Context.Item.Axes.GetChild("listfilterpage");
            FilterPath = Sitecore.Links.LinkManager.GetItemUrl(filterItem);
            SetFilterButtonClass(); //check if filter is active or not
            #endregion

            UpdateIdList();

            #region Check If need to load Invoice
            if (Session["invoiceexport"] != null && !String.IsNullOrEmpty(Session["invoiceexport"].ToString()))
            {
                Session["invoiceexport"] = null;
                LoadExcelFile();
            }
            #endregion


            #region Set Url for Popup
            if (CurrentUser.Type == WorkflowEnums.UserType.NetworkOperator)
            {
                MunicipalityName.Value = "/NetworkOperator/";
            }
            else
            {
                MunicipalityName.Value = string.Format("/{0}/", CurrentUser.Name);
            }
            #endregion

            LoadCssClass();//display status icons for each alert

            #region Set visibility of Save button
            if (CurrentUser.Type == WorkflowEnums.UserType.Municipality &&
                (Sitecore.Context.Item.Name == WorkflowConstants.Executed ||
                Sitecore.Context.Item.Name == WorkflowConstants.NewAlerts))
            {
                btnSave.Visible = true;
            }
            #endregion
        }

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick" && e.Item is Telerik.Web.UI.GridDataItem)
            {
                string alertId = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["id"].ToString();
                String detailPath = String.Empty;
                if (Utils.Utils.GetCurrentItem() == "Search")
                {
                    var list = RadGrid1.DataSource as EstateDataSet.ListAlertRow[];
                    var row = (from r in list
                               where r.id.ToString() == alertId
                               select r).First();
                    detailPath = GetSearchPath((WorkflowEnums.Status)row.currentstatus);
                }
                else
                {
                    Item detailPageItem = Sitecore.Context.Item.Axes.SelectSingleItem("./detailpage");
                    detailPath = Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);
                }
                Response.Redirect(string.Format("{0}?alertId={1}", detailPath, alertId));
            }
            else
            {
                var item = e.Item as GridEditableItem;
                if (item != null)
                {
                    int id = Int32.Parse(item["id"].Text);
                    WorkflowEnums.Status oldStatus = (WorkflowEnums.Status)Int32.Parse(item["currentStatus"].Text);
                    WorkflowEnums.Status? newStatus = null;// by default
                    switch (e.CommandName)
                    {
                        case WorkflowConstants.Approve:
                            newStatus = WorkflowEnums.Status.Approved;
                            break;
                        case WorkflowConstants.PartiallyApprove:
                            break;
                        case WorkflowConstants.Reject:
                            break;
                        case WorkflowConstants.Accept:
                            newStatus = WorkflowEnums.Status.Accepted;
                            break;
                        case WorkflowConstants.Decline:
                            break;
                        case "Unselect":
                            if (OnRemoveSelection != null)
                                OnRemoveSelection(id);
                            break;
                    }
                    if (OnChangeStatus != null && newStatus != null)
                        OnChangeStatus(id, newStatus.Value, oldStatus);

                    Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item));
                }                
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (OnSave != null)
                OnSave();
            Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item));
            UpdateIdList();
        }

        protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgs e)
        {
            UpdateIdList();
            CheckVisibilityGridColumns();
        }

        protected void btnDeleteSelect_Click(object sender, EventArgs e)
        {
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                if ((dataItem.FindControl("itemChkbox") as CheckBox).Checked)
                {
                    UpdateAlertsStatus(dataItem["id"].Text, WorkflowEnums.Status.Deleted, WorkflowEnums.Status.Created);
                }
            }
            SaveChanges();
            RefreshPage();
        }

        protected void btnSendSelected_Click(object sender, EventArgs e)
        {
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                if ((dataItem.FindControl("itemChkbox") as CheckBox).Checked)
                {
                    UpdateAlertsStatus(dataItem["id"].Text, WorkflowEnums.Status.Sent, WorkflowEnums.Status.Created);
                }
            }
            SaveChanges();
            RefreshPage();
        }

        protected void btnSendAll_Click(object sender, EventArgs e)
        {
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                UpdateAlertsStatus(dataItem["id"].Text, WorkflowEnums.Status.Sent, WorkflowEnums.Status.Created);
            }
            SaveChanges();
            RefreshPage();
        }

        protected void btnSendSelectedInvoice_Click(object sender, EventArgs e)
        {
            List<string> ids = new List<string>();
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                if ((dataItem.FindControl("itemChkbox") as CheckBox).Checked)
                {
                    ids.Add(dataItem["id"].Text);
                }
            }
            CreateInvoiceReport(true, ids, null);
            RefreshPage();
        }

        protected void btnSendAllInvoice_Click(object sender, EventArgs e)
        {
            CreateInvoiceReport(true, null, null);
            RefreshPage();
        }

        protected void btnGetPartiallyAccepInvoice_Click(object sender, EventArgs e)
        {
            CreateInvoiceReport(false, null, WorkflowEnums.Status.AcceptedPartially);
            RefreshPage();
        }

        protected void btnSendPartiallyAccepToArchive_Click(object sender, EventArgs e)
        {
            var listOfId = new List<string>();
            foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
            {
                if ((dataItem.FindControl("itemChkbox") as CheckBox).Checked)
                {
                    listOfId.Add(dataItem["id"].Text);
                }
            }
            if (SendToArchiveList != null)
            {
                SendToArchiveList(listOfId);
            }

            RefreshPage();
        }

        #endregion

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (Sitecore.Context.Item.Name == WorkflowConstants.Executed &&
                CurrentUser.Type == WorkflowEnums.UserType.Municipality)
            {
                if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
                {
                    var dataItem = e.Item.DataItem;
                    if (dataItem != null)
                    {
                        if (((DataRowView)dataItem).Row["isherstel"] != null &&
                            ((DataRowView)dataItem).Row["isherstel"] != DBNull.Value&&
                            (bool)((DataRowView)dataItem).Row["isherstel"])
                        {

                            var btn = ((GridDataItem)e.Item)["colAccept"].Controls[0] as Button;
                            if (btn != null)
                            {
                                btn.Enabled= false;
                                //((GridDataItem)e.Item).Visible = false;
                                var classStr = btn.CssClass;
                                if (string.IsNullOrEmpty(classStr))
                                    classStr = "disabled";
                                else
                                    classStr = string.Concat(classStr, " disabled");
                                btn.CssClass = classStr;
                            }
                        }
                    }
                } 
            }
        }
    }
}